<template>
    <!--  <div>
          <router-link to="/addUser">新增歌曲</router-link>
      </div> -->
    <div class="button-container">
      <el-button @click="openDel">批量删除</el-button>
      
      <el-date-picker
        v-model=" attendanceForm.excusedStartTime"
        value-format="YYYY-MM-DD"
        type='date'
        :shortcuts="shortcuts"
        :size="size"
        placeholder="请假开始日期搜索"
         label="日期搜索"
      />
      <el-button   @click="getAttendanceRecords(1)">搜索</el-button>
      <el-button type="primary" @click="addAttendanceRecordsVisible = true" class="right-aligned-button">添加请假申请</el-button>
    </div>
    
    <el-table :data="tableData.records" stripe border @selection-change="handleSelectionChange" style="width: 100%">
      <!-- <el-table-column prop="id" label="Id(一般不展示)" width="180" /> -->
      <el-table-column type="selection" width="40" align="center"></el-table-column>
      <el-table-column prop="userName" label="用户名" width="180" />
      <el-table-column prop="excusedStartTime" label="请假开始时间"  />
      <el-table-column prop="excusedEndTime" label="请假结束时间"  />
      <el-table-column prop="absenceCount" label="缺勤天数"  />
      
      <el-table-column prop="state" label="申请是否通过">
    <template #default="{ row }">
      <span v-if="row.state === '0'">未通过</span>
      <span v-else-if="row.state === '1'">通过</span>
    </template>
  </el-table-column>
      <el-table-column label="操作" width="350" align="center">
        <template v-slot="scope">
          <el-button v-if="scope.row.state !== '0'" plain disabled @click="editRow(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.state !== '1'"  @click="editRow(scope.row)">编辑</el-button>
          <!-- <el-button @click="editRow(scope.row)" >编辑</el-button> -->
          <!-- <el-button type="danger" @click="openCountRow(scope.row.id)">计算缺勤天数</el-button> -->
          <el-button type="danger" @click="openDelRow(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :small="false"
        :page-sizes="[1,10, 20, 30, 40,50]"
        :disabled="false"
        layout="total,sizes, prev, pager, next,jumper"
        :total="dataTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" v-model="editVisible">
      <el-form :model="attendanceForm">
        <el-form-item label="请假开始日期">
        <el-date-picker
        v-model=" attendanceForm.excusedStartTime"
        value-format="YYYY-MM-DD"
        type='date'
        :disabled-date="disabledStartDate"
        :shortcuts="shortcuts"
        :size="size"
         label="请假开始日期"
      />
    </el-form-item>
      <el-form-item label="请假结束日期">
      <el-date-picker
        v-model=" attendanceForm.excusedEndTime"
        value-format="YYYY-MM-DD"
        type='date'
        :disabled-date="disabledDate"
        :shortcuts="shortcuts"
        :size="size"
         label="请假结束日期"
      />
    </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
     <!-- 添加弹出框 -->
     <el-dialog title="请假申请" v-model="addAttendanceRecordsVisible">
      <el-form :model="attendanceForm ">
        <el-form-item label="用户名字">
          <el-input v-model="attendanceForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="请假开始时间">
          <!-- <el-input  v-model="attendanceForm.excusedStartTime"></el-input> -->
          <el-date-picker
        v-model=" attendanceForm.excusedStartTime"
        value-format="YYYY-MM-DD"
        type='date'
        :disabled-date="disabledStartDate"
        :shortcuts="shortcuts"
        :size="size"
        placeholder="请假开始日期"
      />
        </el-form-item>
        <el-form-item label="请假结束时间">
          <!-- <el-input  v-model="attendanceForm.excusedEndTime"></el-input> -->
          <el-date-picker
        v-model=" attendanceForm.excusedEndTime"
        value-format="YYYY-MM-DD"
        type='date'
        :disabled-date="disabledDate"
        :shortcuts="shortcuts"
        :size="size"
        placeholder="请假结束日期"
      />

        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="addAttendanceRecords">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <div>
      <!-- 全部删除提示框 -->
      <el-dialog title="提示" v-model="delVisible" width="300px" center>
        <div align="center">删除不可恢复，是否确定删除？</div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelDel">取 消</el-button>
            <el-button type="primary" @click="deleteAll">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 删除一行提示框 -->
      <el-dialog title="提示" v-model="delRowVisible" width="300px" center>
        <div align="center">删除不可恢复，是否确定删除？</div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelDel">取 消</el-button>
            <el-button type="primary" @click="deleteRow">确 定</el-button>
          </span>
        </template>
      </el-dialog>
       <!-- 计算一行提示框 -->
       <el-dialog title="提示" v-model="countRowVisible" width="300px" center>
        <div align="center">是否计算缺勤天数？</div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelCount">取 消</el-button>
            <el-button type="primary" @click="countRow">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog title="新增歌曲" v-model="addAttendanceVisible" width="800px" center>
        <div>
          <upload-img></upload-img>
        </div>
      </el-dialog>
    </div>
  </template>
    
  <script lang="ts" setup>
  import { ref, onMounted, reactive,computed } from 'vue'
  import emitter from "@/utils/emitter";
  import axiosHttp from '../http/AxiosUtil'
  import uploadImg from '../components/user/uploadImg.vue'
  

   /* -------------日期---------------------- */
const size = ref<'default' >('default')

const value1 = ref('')
const value2 = ref('')

const shortcuts = [
  {
    text: 'Today',
    value: new Date(),
  },
  {
    text: 'Yesterday',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: 'A week ago',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  },
]
const disabledStartDate = (time: Date) => {
  return time.getTime() < Date.now()
}



function disabledDate(time: Date): boolean {
  if (!attendanceForm.excusedStartTime.valueOf) {
    return false; // 如果未选择请假开始日期，不禁用任何日期
  }

  const selectedDate:Date = new Date(attendanceForm.excusedStartTime);
  return time.valueOf() < selectedDate.valueOf(); // 禁用大于请假开始日期的日期
}
  //当前页码
  const currentPage = ref(1)
  //数据总量
  const dataTotal = ref(100)
  //每页数据量
  const pageSize = ref(1)
  /* -------------分页---------------------- */
  //page-size 改变时触发,val点击的数据size
  const handleSizeChange = (val: number) => {
    pageSize.value = val;
    getAttendanceRecords(1);
  }
  //	current-page 改变时触发
  const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    getAttendanceRecords(val)
  }
  //搜索关键字
  const songName = ref()
 
  //打开新增弹窗
  const addAttendanceVisible = ref(false)
  /* 
    需要新增歌曲组件中加入：emitter.emit("cancelAdd", false);这段代码在新增成功后执行
  */
  emitter.on("cancelAdd", (msg) => {
    addAttendanceVisible.value = msg as boolean;
    getAttendanceRecords(1);
  });
  //表格数据
  const tableData = ref({
    records: []
    
  })
  onMounted(() => {
    getAttendanceRecords(1);
  })

  //查询获取歌曲数据
  function getAttendanceRecords(current:number) {
    let param = new FormData();
  param.append('excusedStartTime',attendanceForm.excusedStartTime);
  param.append('size',pageSize.value.toString());
  param.append('current',current.toString())
    axiosHttp.post('/AttendanceRecords/getAttendanceRecords',param ).then(response => {
      let data = response.data
      tableData.value = data;
      dataTotal.value = data.total
    })
  }
  
  /**
     * 编辑
     */
  const editVisible = ref(false);
  
  const attendanceForm = reactive({
    id:"",
    userName: "",
    excusedStartTime: "",
    excusedEndTime: "",   
  });

  /* 打开弹窗 */
  function editRow(row: any) {
    attendanceForm.id = row.id;
    attendanceForm.excusedStartTime = row.excusedStartTime;
    attendanceForm.excusedEndTime = row.excusedEndTime;
    editVisible.value = true;
    openCountRow(row.id);
   
  }
  //保存更新
  function saveEdit() {
    const token = localStorage.getItem('Token')
    let param: any = new FormData();
    param.append('id', attendanceForm.id);
    param.append('excusedStartTime', attendanceForm.excusedStartTime);
    param.append('excusedEndTime', attendanceForm.excusedEndTime);
    if (fileList.value.length > 0) {
      param.append('fm', fileList.value[0].raw);
    }
    //在这等价于上方的formData
    // const param = {
    //   id:editForm.id,
    //   songName:editForm.songName,
    //   geci:editForm.geci,    
    //   fm:Object,
    // }
    if (fileList.value.length > 0) {
      param.fm = fileList.value[0].raw;
    }
    axiosHttp.post('/AttendanceRecords/UpdateAttendance', param, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
      .then(response => {
        if (response.data.code == '1') {
          ElMessage.info("更新成功！")
          countRow();
          attendanceForm.excusedStartTime='';

          getAttendanceRecords(currentPage.value);
          cancel()
        }
      })
  }
  function addAttendanceRecords(){
    let param: any = new FormData();
    param.append('userName',attendanceForm.userName);
    param.append('excusedStartTime', attendanceForm.excusedStartTime);
    param.append('excusedEndTime', attendanceForm.excusedEndTime);

    axiosHttp.post('/AttendanceRecords/saveAttendanceRecordsService', param, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
      .then(response => {
        if (response.data.code == '1') {
          ElMessage.info("添加成功！")
          attendanceForm.excusedStartTime='';
          getAttendanceRecords(currentPage.value);
          cancel()
        }
      })
  }
  function cancel() {
    editVisible.value=false;
    addAttendanceRecordsVisible.value = false;
    if (fileList.value.length > 0) {
      fileList.value.pop();
    }
    
  }
  /**
  * 删除
  */
  const idx = ref<String>("-1"); // 记录当前要删除的行
  const multipleSelection: any = ref([]); // 记录当前要删除的列表
  const delVisible = ref(false); // 显示删除框
  const delRowVisible = ref(false); // 显示删除一行框
  const countVisible = ref(false); // 显示计算框
  const countRowVisible = ref(false); // 显示计算一行框
  const addAttendanceRecordsVisible=ref(false);//显示添加请假
  
  async function confirm() {
  
  }
  function handleSelectionChange(val: any) {
    multipleSelection.value = val;
  }
  
  function deleteRow() {
    let ids = [idx.value];
    deleteRequest(ids);
  }
  function countRow() {
    let ids = [idx.value];
    countRequest(ids);
  }
  //打开删除窗
  function openDelRow(id: String) {
    delRowVisible.value = true
    idx.value = id
  }
  //  打开删除确认窗
  function openDel() {
    delVisible.value = true;
  }
  //关闭删除窗
  function cancelDel() {
    delVisible.value = false;
    delRowVisible.value = false;
  }

  //打开计算窗
  function openCountRow(id: String) {
    //countRowVisible.value = true
    idx.value = id
  }
  //关闭计算窗
  function cancelCount() {
    countVisible.value = false;
    countRowVisible.value = false;
  }
  //请求后端的删除接口
  function deleteRequest(ids: any) {
    axiosHttp.post('/AttendanceRecords/delAttendanceRecords', JSON.stringify(ids), {
      headers: {
        'Content-Type': 'application/json'//后端接口的参数需要加上@RequestBody
      }
    })
      .then(response => {
        if (response.data.code == '1') {
          ElMessage.info("删除成功！")
          cancelDel()
          multipleSelection.value = [];
          getAttendanceRecords(1);
        } else {
          ElMessage.error("删除失败！")
        }
      })
  }
  //请求后端的计算接口
  function countRequest(ids: any) {
    axiosHttp.post('/AttendanceRecords/qingJiaTianShu', JSON.stringify(ids), {
      headers: {
        'Content-Type': 'application/json'//后端接口的参数需要加上@RequestBody
      }
    })
      .then(response => {
        if (response.data.code == '1') {
          ElMessage.info("计算成功！")
          cancelCount()
          multipleSelection.value = [];
          getAttendanceRecords(1);
        } else {
          ElMessage.error("计算失败！")
        }
      })
  }
  //删除请求
  function deleteAll() {
    let ids = [];
    for (let item of multipleSelection.value) {
      ids.push(item.id)
    }
    deleteRequest(ids)
  }
  /* -------------------------图片上传------------------------------ */
  import { type UploadProps, type UploadFile, type UploadFiles, type UploadUserFile, type UploadRawFile, type UploadInstance, ElDialog } from 'element-plus'
  
  //上传的文件信息
  const fileList = ref<UploadUserFile[]>([])
  //绑定的上传组件
  const upload = ref<UploadInstance>()
  
  
  
  //超出上传数量时触发的方法
  const handleExceed: UploadProps['onExceed'] = (files) => {
    //"!" 强制链式调用
    //替换预览图片
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    upload.value!.handleStart(file)
  
    //用来保存图片，用以上传
    fileList.value.splice(0, 1, file)
  }
  /* -------------------------图片上传结束------------------------------ */
  /* data类型Url的形式：
    data:,<文本数据>
  
    data:text/plain,<文本数据>
  
    data:text/html,<HTML代码>
  
    data:text/html;base64,<base64编码的HTML代码>
  
    data:text/css,<CSS代码>
  
    data:text/css;base64,<base64编码的CSS代码>
  
    data:text/javascript,<Javascript代码>
  
    data:text/javascript;base64,<base64编码的Javascript代码>
  
    编码的gif图片数据
  
    编码的png图片数据
  
    编码的jpeg图片数据
  
    编码的icon图片数据
    */
  </script>
  
<style scoped>
.button-container {
  display: flex;
  justify-content: flex-end;
}

.right-aligned-button {
  margin-left: auto;
}
</style>